<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright  Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * Adminhtml sales order creditmemo controller
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
/*
 *Array
(
    [146501] =&gt; Array
        (
            [qty] =&gt; 20
        )

    [146502] =&gt; Array
        (
            [qty] =&gt; 4
        )

    [146503] =&gt; Array
        (
            [qty] =&gt; 4
        )

    [146504] =&gt; Array
        (
            [qty] =&gt; 4
        )

    [146505] =&gt; Array
        (
            [qty] =&gt; 4
        )

    [146506] =&gt; Array
        (
            [qty] =&gt; 4
        )

)
Array
(
    [items] =&gt; Array
        (
            [146501] =&gt; Array
                (
                    [qty] =&gt; 20
                )

            [146502] =&gt; Array
                (
                    [qty] =&gt; 4
                )

            [146503] =&gt; Array
                (
                    [qty] =&gt; 4
                )

            [146504] =&gt; Array
                (
                    [qty] =&gt; 4
                )

            [146505] =&gt; Array
                (
                    [qty] =&gt; 4
                )

            [146506] =&gt; Array
                (
                    [qty] =&gt; 4
                )

        )

    [do_offline] =&gt; 1
    [comment_text] =&gt;
    [shipping_amount] =&gt; 0
    [adjustment_positive] =&gt; 0
    [adjustment_negative] =&gt; 0
    [refund_points] =&gt; 0
    [refund_earned_points] =&gt; 816
    [qtys] =&gt; Array
        (
            [146501] =&gt; 20
            [146502] =&gt; 4
            [146503] =&gt; 4
            [146504] =&gt; 4
            [146505] =&gt; 4
            [146506] =&gt; 4
        )

)

 * */
require_once("Mage/Adminhtml/controllers/Sales/Order/CreditmemoController.php");


class Silk_Zgb_Adminhtml_Order_CreditmemoController extends Mage_Adminhtml_Sales_Order_CreditmemoController
{


     /**
     * Save creditmemo
     * We can save only new creditmemo. Existing creditmemos are not editable
     */
    public function saveAction()
    {
        $data = $this->getRequest()->getPost('creditmemo');
        if (!empty($data['comment_text'])) {
            Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
        }

        try {
            $od = Mage::getModel('sales/order')->load($this->getRequest()->getParam('order_id'));
            $status = $od->getStatus();
            $mtype = 1;
            if($od->getStatus()=='complete_order')
            {
                $mtype = 0;
            }
            $creditmemo = $this->_initCreditmemo();
            if ($creditmemo) {
                if (($creditmemo->getGrandTotal() <=0) && (!$creditmemo->getAllowZeroGrandTotal())) {
                    Mage::throwException(
                        $this->__('Credit memo\'s total must be positive.')
                    );
                }

                $comment = '';
                if (!empty($data['comment_text'])) {
                    $creditmemo->addComment(
                        $data['comment_text'],
                        isset($data['comment_customer_notify']),
                        isset($data['is_visible_on_front'])
                    );
                    if (isset($data['comment_customer_notify'])) {
                        $comment = $data['comment_text'];
                    }
                }

                if (isset($data['do_refund'])) {
                    $creditmemo->setRefundRequested(true);
                }
                if (isset($data['do_offline'])) {
                    $creditmemo->setOfflineRequested((bool)(int)$data['do_offline']);
                }

                $creditmemo->register();
                if (!empty($data['send_email'])) {
                    $creditmemo->setEmailSent(true);
                }

                $creditmemo->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
                $creditmemo->setSource($mtype);
                $this->_saveCreditmemo($creditmemo);
                $order = Mage::getModel('sales/order')->load($creditmemo->getOrder()->getId());

                if($order->canCreditmemo() && $order->getState()=="complete")
                {
                    $order->addStatusToHistory($status, '创建退款/退货单:'.$creditmemo->getIncrementId());
                    $order->setStatus($status)->save();
                }
                //after save process back to stock

                /**
                 * Process back to stock flags
                 */
//                foreach ($creditmemo->getAllItems() as $creditmemoItem) {
//                    $orderItem = $creditmemoItem->getOrderItem();
//                    $parentId = $orderItem->getParentItemId();
//
//                    if($creditmemoItem->getBackToStock())
//                    {
//                        $qty = $creditmemoItem->getQty();
//                        $productId = $creditmemoItem->getProductId();
//                        $operation = 1;
//
//                        $session = Mage::getSingleton('admin/session');
//                        $adminId = $session->getUser()->getId();
//
//                        $date = date("Y-m-d H:i:s");
//                        $resource = Mage::getSingleton('core/resource');
//                        $db = $resource->getConnection('core_read');
//
//                        $store = Mage::getModel('core/store')->load($orderItem->getStoreId());
//                        $websiteId = $store->getWebsiteId();
//                        $order = Mage::getModel('sales/order')->load($creditmemo->getOrderId());
//                        $orderId = $order->getIncrementId();
//
//                        $comment = "订单退款返还库存,订单号{$orderId}.";
//
//                        $sql = "insert into aitoc_inventory_stock(website_id,product_id,qty,operation,order_id,created_at,admin_id,comment)
//                        values('{$websiteId}','{$productId}','{$qty}','{$operation}','{$orderId}','{$date}','{$adminId}','{$comment}')";
//                        //Mage::log($sql);
//                        $db->exec($sql);
//
//                    }
//                }


                $creditmemo->sendEmail(!empty($data['send_email']), $comment);
                $this->_getSession()->addSuccess($this->__('The credit memo has been created.'));
                Mage::getSingleton('adminhtml/session')->getCommentText(true);
                $this->_redirect('*/sales_order/view', array('order_id' => $creditmemo->getOrderId()));
                return;
            } else {
                $this->_forward('noRoute');
                return;
            }
        } catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
            Mage::getSingleton('adminhtml/session')->setFormData($data);
        } catch (Exception $e) {
            Mage::logException($e);
            $this->_getSession()->addError($this->__('Cannot save the credit memo.'));
        }
        $this->_redirect('*/*/new', array('_current' => true));
    }

    public function cancelOrderAction()
    {
        $orderId = $this->getRequest()->getParam('order_id');
        $orderIds = $this->getRequest()->getParam('order_ids');

        if($orderId && !$orderIds)
        {
            $orderIds = array($orderId);
        }
        foreach($orderIds as $id)
        {
            $order = Mage::getModel('sales/order')->load($id);
            $rewordpoins = $order->getRewardpointsDiscount();
            //add by wanglin start
            if($order->getStatus() == 'processing' ){
               // if($order->getGrandTotal()==0){
                    //积分返回
                    $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
                    if ($customer->getId()) {
                        $maxPoint  = $order->getRewardpointsSpent();
                        $maxPoint -= (int)Mage::getResourceModel('rewardpoints/transaction_collection')
                            ->addFieldToFilter('action', 'spending_cancel')
                            ->addFieldToFilter('order_id', $order->getId())
                            ->getFieldTotal();
                        if ($maxPoint > 0) {
                            $order->setRefundSpentPoints($maxPoint);
                            if (empty($customer)) {
                                $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
                            }
                            Mage::helper('rewardpoints/action')->addTransaction(
                                'spending_cancel', $customer, $order
                            );
                        }
                    }
                    //兑换数量返回
                    $items = $order->getAllItems();
                    $increment_id = $order->getIncrementId();
                    foreach ($items as $item) {
                        $qutoeItem = Mage::getModel('sales/quote_item')->load($item->getQuoteItemId());
                        $exchange = $qutoeItem->getExchange();
                        if ($exchange) {
                            $activityId = $qutoeItem->getActivityId();
                            $productId = $qutoeItem->getProductId();
                            $collection = Mage::getResourceModel('pms/exchangeproduct_collection');
                            $collection->addFieldToFilter('activity_id', $activityId)
                                ->addFieldToFilter('product_id', $productId);
                            $exchangeProduct = $collection->getFirstItem();
                            $qtynums = (int)$exchangeProduct->getExchangedQty() - (int)$qutoeItem->getQty();
                            if ($exchangeProduct && $exchangeProduct->getId() && $qtynums >= 0) {
                                $exchangeProduct->setExchangedQty($qtynums);
                                $exchangeProduct->save();
                            }
                        }
                    }
               // }else{
                    $items = $order->getAllItems();
                    foreach ($items as $item) {
                        $qutoeItem = Mage::getModel('sales/quote_item')->load($item->getQuoteItemId());
                        $gift_id   = $qutoeItem->getGiftId();
                        $productId = $qutoeItem->getProductId();
                        $exchange  = $qutoeItem->getExchange();
                        //待处理状态取消订单后赠送商品处理
                        if($gift_id>0 && $gift_id){
                            //已赠数量返回
                            $giftmodel = Mage::getModel("pms/gift")->load($gift_id);
                            $giftqtynums = (int)$giftmodel->getUsedQty()-(int)$qutoeItem->getQty();
                            if ($giftmodel && $giftmodel->getId() && $giftqtynums>=0) {
                                $giftmodel->setUsedQty($giftqtynums);
                                $giftmodel->save();
                            }
                        }

                        //缺货状态改为有货
                        $storeId = $item->getStoreId();
                        $store = Mage::getModel('core/store')->load($storeId);
                        $websiteId = $store->getWebsiteId();
                        $collection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');
                        $collection->addAttributeToFilter('entity_id',$productId);
                        if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
                            $collection->joinField('is_in_stock',
                                'cataloginventory/stock_item',
                                'is_in_stock',
                                'product_id=entity_id',
                                '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $websiteId,
                                'left');
                        }
                        $product = $collection->getFirstItem();
                        $resource= Mage::getSingleton('core/resource');
                        $db      = $resource ->getConnection('core_write');
                        //积分商品返回库存
                        /*$stockItem = Mage::getModel('cataloginventory/stock_item')->setStoreId($storeId)->loadByProduct($productId);
                        $originQty = $stockItem->getQty();
                        $resource   = Mage::getSingleton('core/resource');
                        $db         =   $resource ->getConnection('core_write');*/

                        /*if($exchange>0){
                            $Qtyorder = (int)$qutoeItem->getQty();
                            $totalqty = $originQty+$Qtyorder;
                            $date = date('Y-m-d H:i:s',time());
                            $comment = '订单'.$increment_id.'取消退货';
                            $sql2 = "insert into aitoc_inventory_stock(website_id,product_id,qty,operation,order_id,created_at,admin_id,comment)
    			values('{$websiteId}','{$productId}','{$Qtyorder}','1','{$increment_id}','{$date}','1','$comment')";
                            $db->query($sql2);
                            $sql1 = "UPDATE `aitoc_cataloginventory_stock_item` SET qty='{$totalqty}' WHERE product_id='{$productId}' and website_id='{$websiteId}'";
                            $db->query($sql1);
                        }*/
                        if($product->getIsInStock()==0){
                            $sql = "UPDATE `aitoc_cataloginventory_stock_item` SET is_in_stock=1 WHERE product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1 and is_in_stock=0";
                            $db->query($sql);
                        }
                    }
               // }
            }
            $creditmemo = $this->_initCreditmemoByOrder($order);
            $creditmemo->register();
            $creditmemo->setEmailSent(false);
            $creditmemo->getOrder()->setCustomerNoteNotify(false);
            $creditmemo->setSource(1);
            $creditmemo->setState(Mage_Sales_Model_Order_Creditmemo::STATE_REFUNDED);
            Mage::unregister('current_creditmemo');
            Mage::register('current_creditmemo', $creditmemo);
            $this->_saveCreditmemo($creditmemo);

            //add by wanglin start 修改订单状态

            //修改订单状态
            if($rewordpoins>0){
                $write = Mage::getSingleton('core/resource')->getConnection('core_write');
                $sql1 = "update sales_flat_order set state='closed',status='closed' where entity_id='{$id}'";
                $write->query($sql1);
                $sql2 = "update sales_flat_order_grid set status='closed' where entity_id='{$id}'";
                $write->query($sql2);
            }
            //add by wanglin end
        }
        $this->_getSession()->addSuccess("订单已取消!");
        if($orderId)
        {
            $this->_redirect('adminhtml/sales_order/view',array('order_id'=>$orderId));
        }
        else
        {
            $this->_redirect('adminhtml/sales_order/index');
        }
    }



    public function _initCreditmemoByOrder($order)
    {
        $invoice = $this->_initInvoice($order);

        $data = array();
        $data['do_offline'] = 1;
        $data['refund_earned_points'] = $order->getRewardpointsEarn();
        $savedData = $this->getItemData($order);
        $data['items'] = $savedData;
        $qtys = array();
        $backToStock = array();
        foreach ($savedData as $orderItemId =>$itemData) {
            if (isset($itemData['qty'])) {
                $qtys[$orderItemId] = $itemData['qty'];
            }
            if (isset($itemData['back_to_stock'])) {
                $backToStock[$orderItemId] = true;
            }
        }
        $data['qtys'] = $qtys;

        $service = Mage::getModel('sales/service_order', $order);
        if ($invoice) {
            $creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);
        } else {
            $creditmemo = $service->prepareCreditmemo($data);
        }

        /**
         * Process back to stock flags
         */
        foreach ($creditmemo->getAllItems() as $creditmemoItem) {
            $orderItem = $creditmemoItem->getOrderItem();
            $parentId = $orderItem->getParentItemId();
            if (isset($backToStock[$orderItem->getId()])) {
                $creditmemoItem->setBackToStock(true);
            } elseif ($orderItem->getParentItem() && isset($backToStock[$parentId]) && $backToStock[$parentId]) {
                $creditmemoItem->setBackToStock(true);
            } elseif (empty($savedData)) {
                $creditmemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
            } else {
                $creditmemoItem->setBackToStock(false);
            }
        }

        $args = array('creditmemo' => $creditmemo, 'request' => $this->getRequest());
        Mage::dispatchEvent('adminhtml_sales_order_creditmemo_register_before', $args);
        return $creditmemo;
    }

    public function getItemData($order)
    {
        $data = array();
        $items = $order->getAllItems();
        foreach($items as $item)
        {
            $data[$item->getId()] = array('qty'=>$item->getQtyOrdered(),'back_to_stock'=>true);
        }
        return $data;
    }

    public function printmemoAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }
}
